<template>
  <div class="consult-reply-management">
    <h4>首页 <el-text>/咨询回复管理</el-text></h4>
    <div>
      <el-form :inline="true">
        <el-form-item label="搜索内容">
          <el-input
              placeholder="请输入咨询类型、内容或回复"
              v-model="searchContent"
              clearable
              @clear="handleSearchClear"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="danger" @click="batchDelete" :disabled="selectedRows.length === 0">
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
        :data="tableData"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="name" label="咨询师" width="120" align="center"></el-table-column>
      <el-table-column prop="type" label="咨询类型" width="120" align="center"></el-table-column>
      <el-table-column prop="time" label="咨询时间" width="180" align="center"></el-table-column>
      <el-table-column prop="content" label="咨询内容" show-overflow-tooltip></el-table-column>
      <el-table-column prop="reply" label="回复内容" show-overflow-tooltip></el-table-column>
      <el-table-column prop="state" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.state === 1 ? 'success' : 'warning'">
            {{ scope.row.state === 1 ? '已回复' : '未回复' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button
              size="small"
              @click="handleReply(scope.row)"
              :disabled="scope.row.state === 1"
          >
            回复
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />
    </div>

    <!-- 回复对话框 -->
    <el-dialog v-model="replyVisible" title="回复咨询" width="50%">
      <el-form label-width="100px">
        <el-form-item label="咨询内容：">
          <el-input
              v-model="currentReplyRow.content"
              type="textarea"
              :rows="3"
              readonly
          ></el-input>
        </el-form-item>
        <el-form-item label="回复内容：" required>
          <el-input
              v-model="replyContent"
              type="textarea"
              :rows="5"
              placeholder="请输入回复内容"
              maxlength="500"
              show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="replyVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReply">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {ElMessage, ElMessageBox, ElPagination} from 'element-plus'
import axios from 'axios'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)

// 分页参数
const size = ref('default');
const currentPage = ref(1)
const pageNum = ref(1)
const pageSize = ref(5)

// 搜索参数
const searchContent = ref('')

// 选中行
const selectedRows = ref([])

// 回复对话框
const replyVisible = ref(false)
const currentReplyRow = ref({})
const replyContent = ref('')

// 加载数据
const fetchData = async () => {
  try {
    loading.value = true


   const response = await axios.get("/api/admin/allreply",{
     params: {
       pageNum: currentPage.value,
       pageSize: pageSize.value,
     }
   });
    const data = response.data.data;
    tableData.value = data.list;
    total.value = data.total;
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = async () => {
  try {
    loading.value = true
    currentPage.value = 1 // 搜索时重置到第一页

    if (!searchContent.value.trim()) {
      await fetchData()
      return
    }


    const response = await axios.get('/api/admin/search', { params })

    if (response.data.code === 200) {
      tableData.value = response.data.data || []
      total.value = response.data.total || 0
      ElMessage.success('搜索成功')
    } else {
      ElMessage.error(response.data.message || '搜索失败')
    }
  } catch (error) {
    console.error('搜索出错:', error)
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 清空搜索
const handleSearchClear = () => {
  currentPage.value = 1
  fetchData()
}

// 分页变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 回复操作
const handleReply = (row) => {
  currentReplyRow.value = { ...row }
  replyContent.value = row.reply || ''
  replyVisible.value = true
}

// 确认回复
const confirmReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空')
    return
  }

  try {
    loading.value = true
    const response = await axios.post('/api/admin/reply', {
      id: currentReplyRow.value.id,
      reply: replyContent.value
    })

    if (response.data.code === 200) {
      ElMessage.success('回复成功')
      replyVisible.value = false
      // 刷新当前页数据
      if (searchContent.value.trim()) {
        await handleSearch()
      } else {
        await fetchData()
      }
    } else {
      ElMessage.error(response.data.message || '回复失败')
    }
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 删除操作
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const response = await axios.delete('/api/admin/delete', { params: { id } })

      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        // 如果当前页只剩一条数据且不是第一页，则返回上一页
        if (tableData.value.length === 1 && currentPage.value > 1) {
          currentPage.value -= 1
        }
        // 刷新数据
        if (searchContent.value.trim()) {
          await handleSearch()
        } else {
          await fetchData()
        }
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户点击取消
  })
}

// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRows.value.length} 条记录吗?`,
        '警告',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )

    loading.value = true
    const ids = selectedRows.value.map(row => row.id)
    const response = await axios.post('/api/admin/batchDelete', ids, {
      headers: { 'Content-Type': 'application/json' }
    })

    if (response.data.code === 200) {
      ElMessage.success(`成功删除 ${response.data.data} 条记录`)
      selectedRows.value = []
      // 刷新数据
      if (searchContent.value.trim()) {
        await handleSearch()
      } else {
        await fetchData()
      }
    } else {
      ElMessage.error(response.data.message || '批量删除失败')
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(`批量删除失败: ${error.response.data.message || error.message}`)
    } else if (error.request) {
      ElMessage.error('服务器无响应，请检查网络连接')
    } else {
      ElMessage.error('请求设置出错: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.consult-reply-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}

.el-pagination {
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-table__cell) {
  padding: 8px 0;
}

:deep(.el-text) {
  color: var(--el-text-color-secondary);
}
</style>